<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3-Promise发送Ajax请求并处理回调地狱问题</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

    <style></style>
  </head>
  <body>
    <div id="app"></div>
    <script>
      // 1：使用原生ajax和pormise移除处理，处理数据的请求发送
      function getData(url) {
        var pMise = new Promise(function (resolve, reject) {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            if (xhr.readyState != 4) return;
            if (xhr.readyState == 4 && xhr.status == 200) {
              resolve(xhr.responseText);
            } else {
              reject('服务器错误');
            }
          };
          xhr.open('get', url);
          xhr.send(null);
        });
        return pMise;
      }

      // 1.1： 请求单个接口数据
      // getData('http://www.localhost:3000/data').then(
      //   function (data) {
      //     console.log(data);
      //   },
      //   function (info) {
      //     console.log(info);
      //   }
      // );

      // 1.2: 发送多个Ajax请求，并保证了顺序
      getData('http://www.localhost:3000/data')
        .then(function (data) {
          console.log(data);
          return getData('http://www.localhost:3000/data1');
        })
        .then(function (data) {
          console.log(data);
          return getData('http://www.localhost:3000/data2');
        })
        .then(function (data) {
          console.log(data);
        });
    </script>
  </body>
</html>
